const axios = require('axios');

const BASE_URL = 'http://localhost:3000';

async function basicExample() {
    console.log('=== SimpleDistCache 使用示例 ===\n');

    try {
        // 1. 写入缓存
        console.log('1. 写入缓存...');
        await axios.post(`${BASE_URL}/cache`, {
            key: 'user:1001',
            value: { name: '张三', age: 25, city: '北京' },
            ttl: 60000 // 60秒
        });
        console.log('✅ 缓存写入成功\n');

        // 2. 读取缓存
        console.log('2. 读取缓存...');
        const response = await axios.get(`${BASE_URL}/cache/user:1001`);
        console.log('✅ 读取结果:', response.data);
        console.log();

        // 3. 写入多个缓存项
        console.log('3. 写入多个缓存项...');
        const items = [
            { key: 'product:1', value: { name: 'iPhone 15', price: 5999 } },
            { key: 'product:2', value: { name: 'MacBook Pro', price: 12999 } },
            { key: 'product:3', value: { name: 'iPad Air', price: 3999 } }
        ];

        for (const item of items) {
            await axios.post(`${BASE_URL}/cache`, item);
        }
        console.log('✅ 批量写入完成\n');

        // 4. 查看集群状态
        console.log('4. 查看集群状态...');
        const nodesResponse = await axios.get(`${BASE_URL}/nodes`);
        console.log('✅ 集群节点:', nodesResponse.data);
        console.log();

        // 5. 删除缓存
        console.log('5. 删除缓存...');
        await axios.delete(`${BASE_URL}/cache/product:2`);
        console.log('✅ 缓存删除成功\n');

        // 6. 验证删除
        console.log('6. 验证删除...');
        try {
            await axios.get(`${BASE_URL}/cache/product:2`);
        } catch (error) {
            if (error.response && error.response.status === 404) {
                console.log('✅ 确认缓存已删除');
            }
        }

    } catch (error) {
        console.error('❌ 操作失败:', error.response?.data || error.message);
    }
}

// 运行示例
if (require.main === module) {
    basicExample();
}

module.exports = basicExample;
